﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Video.DirectShow;  //摄像头
using AForge.Imaging;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net.Http;
using System.Data.SqlClient;




namespace MyTest
{
    /// <summary>
    /// 教员:薛海
    /// 微信:xuehai03
    /// QQ:289477003
    /// 人脸识别
    /// 2019-2-20
    /// </summary>
    public partial class frmFaces : Form
    {
        public frmFaces()
        {
            InitializeComponent();
        }

         //Api_Key
        public static string Api_Key = "DsvIZKqpZahq23VPo71njLgp";
        //Secret_Key
        public static string Secret_Key = "aV4h4RPtbGNKr5ChbZChEhGnChPpIHwy";
        FilterInfoCollection videoDevices;
        VideoCaptureDevice videoSource;
        public int selectedDeviceIndex = 0;
        public int selectedPICIndex = 0;


        private void btnOpen_Click(object sender, EventArgs e)
        {
          
            //连接摄像头。
            videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString);
            videoSource.VideoResolution = videoSource.VideoCapabilities[selectedDeviceIndex];
            // 枚举所有摄像头支持的像素，设置拍照为1920*1080
            foreach (VideoCapabilities capab in videoSource.VideoCapabilities)
            {
                if (selectedPICIndex == 0)
                {
                    if (capab.FrameSize.Width == 1920 && capab.FrameSize.Height == 1080)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                    if (capab.FrameSize.Width == 1280 && capab.FrameSize.Height == 720)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                }
                else
                {
                    if (capab.FrameSize.Width == 1280 && capab.FrameSize.Height == 720)
                    {
                        videoSource.VideoResolution = capab;
                        break;
                    }
                }
            }
            videoSourcePlayer1.VideoSource = videoSource;

            // set NewFrame event handler
            videoSourcePlayer1.Start();

            
        }

        private void frmFaces_Load(object sender, EventArgs e)
        {
            //实例化设备对象
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            if (videoDevices.Count == 0)
            {
                throw new ApplicationException();
            }

            foreach (FilterInfo item in videoDevices)
            {
                //加载设备到下拉框中
                this.comboBox1.Items.Add(item.Name);
            }

            this.comboBox1.SelectedIndex = 0;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {

            if (videoSource == null)
                return;

            Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
            //图片名称，年月日时分秒毫秒.jpg
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".jpg";

            //获取项目的根目录
            String path = AppDomain.CurrentDomain.BaseDirectory;

            //将图片保存在服务器里面
            bitmap.Save(path + "\\picture\\" + fileName, ImageFormat.Jpeg);
            bitmap.Dispose();

            //进行面部特征识别
            facemodel facem = face_test.FaceDetect(path + "\\picture\\" + fileName);
            this.label4.Text = facem.age;      //年龄
            this.label5.Text = facem.beauty;  //漂亮度
            string expression = facem.expression;//表情
            if (expression.Equals("0"))
            {
                this.label7.Text = "不笑";
            }
            else if (expression.Equals("1"))
            {
                this.label7.Text = "微笑";
            }
            else if (expression.Equals("2"))
            {
                this.label7.Text = "大笑";
            }
            string gender = facem.gender;//性别
            if (gender.Equals("male"))
            {
                this.label9.Text = "男";
            }
            else
            {
                this.label9.Text = "女";
            }
            string glasses = facem.glasses;//是否戴眼镜
            if (glasses.Equals("0"))
            {
                this.label11.Text = "无眼镜";
            }
            else if (glasses.Equals("1"))
            {
                this.label11.Text = "普通眼镜";
            }
            else
            {
                this.label11.Text = "墨镜";
            }
            string race = facem.race;//人种
            if (race.Equals("yellow"))
            {
                this.label13.Text = "黄人";
            }
            else if (race.Equals("white"))
            {
                this.label13.Text = "白人";
            }
            else if (race.Equals("black"))
            {
                this.label13.Text = "黑人";
            }
            else if (race.Equals("arabs"))
            {
                this.label13.Text = "棕人";
            }


                    

        }


        public static String TOKEN = "15475231";
 
       

        public static String getAccessToken()
        {
            String authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
            paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair<string, string>("client_id", Api_Key));
            paraList.Add(new KeyValuePair<string, string>("client_secret", Secret_Key));
 
            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            String result = response.Content.ReadAsStringAsync().Result;
            //Console.WriteLine(result);
            return result;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Users users = FaceIdentifys(SavePicture());
            this.label1.Text = users.age.ToString();
            this.label2.Text = users.name;
            this.label6.Text = users.phone;
            this.label9.Text = users.address;
            if (users.picture != null)
            {
                this.pictureBox1.Image = Image.FromFile(users.picture, false);
            }

           
        }

        public string SavePicture()
        {
            if (videoSource == null)
            {
                return null;
            }

            Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
            //图片名称，年月日时分秒毫秒.jpg
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".jpg";

            //获取项目的根目录
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string picture = path + "\\picture\\" + fileName;
            //将图片保存在服务器里面
            bitmap.Save(picture, ImageFormat.Jpeg);
            bitmap.Dispose();
            return picture;
        }



        public static Users FaceIdentifys(string filename)
        {
            long id = 0;
            string ids = "";
            double scores_num = 0;
            Users user = new Users();
            var client = new Baidu.Aip.Face.Face(Api_Key, Secret_Key);
            var image1 = File.ReadAllBytes(filename);
            var result = user.Identify(image1, new[] { "gr_test" }, 1, 1);
            //先判断脸是不是在上面，在继续看有匹配的没，否则提示放上脸
            //得到根节点
            JObject jo_result = (JObject)JsonConvert.DeserializeObject(result.ToString());
            if ((string)jo_result["error_msg"] != null)
            {
                MessageBox.Show("对不起，请把脸放上！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            else
            {
                //检测到脸
                //得到result节点
                JArray jo_age = (JArray)JsonConvert.DeserializeObject(jo_result["result"].ToString());
                foreach (var val in jo_age)
                {
                    id = long.Parse(((JObject)val)["uid"].ToString());  //获取uid
                    string scores = ((JObject)val)["scores"].ToString();//获取scores
                    int num1 = scores.IndexOf("\n") + 2;
                    int num2 = scores.LastIndexOf("]")-8;
                    ids = scores.Substring(num1, num2);
                    scores_num =double.Parse(ids);
                }
                if (scores_num > 80)
                {
                    user = QueryUsersById(id);
                    if (user.id != 0)
                    {
                        MessageBox.Show("签到成功，已检测到您的信息", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("对不起，系统根据您的脸未检测到信息", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                }
                else {
                    MessageBox.Show("对不起，系统根据您的脸未检测到信息", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }

            }
            return user;

        }

         public static Users QueryUsersById(long id)
        {

            Users user = new Users();
            string sql = "select * from users where id = @id";
            using (SqlDataReader reader = SqlHelper.ExcuteReader(sql, CommandType.Text, new SqlParameter("@id", id)))
            {
                if (reader.Read())
                {
                    user.id = long.Parse(reader[0].ToString());
                    user.name = reader[1].ToString();
                    user.age = Convert.ToInt32(reader[2]);
                    user.phone = reader[3].ToString();
                    user.password = reader[4].ToString();
                    user.address = reader[5].ToString();
                    user.picture = reader[6].ToString();
                }
            }
            return user;
        }



        private void button2_Click(object sender, EventArgs e)
        {
            if (videoSource == null)
            {
                MessageBox.Show("请先打开摄像头");
            }
            else
            {
                this.videoSourcePlayer1.SignalToStop();
                this.videoSourcePlayer1.WaitForStop();
            }
        }


        }
    
}
